package com.cb.orderservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cb.orderservice.entity.TOrder;
import com.cb.orderservice.service.TOrderService;
import com.cb.utils.JwtUtils;
import com.cb.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.management.OperatingSystemMXBean;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Cebb
 * @since 2020-06-29
 */
@Api("订单管理")

@RestController
@RequestMapping("/orderservice/order")
public class TOrderController {

    private final TOrderService orderService;

    @Autowired
    public TOrderController(TOrderService orderService) {
        this.orderService = orderService;
    }

    @ApiOperation("根据课程id生成订单")
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable("courseId") String courseId, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        // 创建订单, 返回订单号
        String orderNo = orderService.createOrder(courseId, memberId);

        return R.ok().data("orderId", orderNo);
    }

    @ApiOperation("根据订单号查询订单信息")
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderId);
        TOrder order = orderService.getOne(wrapper);

        return R.ok().data("item", order);
    }

    @ApiOperation("根据课程id和用户id查询订单表中的订单状态")
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable("courseId") String courseId,
                               @PathVariable("memberId") String memberId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        wrapper.select("status");
        wrapper.last("limit 1");

        TOrder order = orderService.getOne(wrapper);
        if (order == null) { return false; }

        // =1: 已支付 , =0: 未支付
        return order.getStatus() == 1;
    }

}

